import { NextRequest, NextResponse } from 'next/server';
import { VideoService } from '@/app/lib/DataBase/database';

// 模拟获取当前用户ID的函数（实际项目中应该从认证系统获取）
const getCurrentUserId = (request: NextRequest): string => {
  // 在实际项目中，这里应该从JWT token或session中获取用户ID
  // 这里为了演示，我们使用一个固定值或从查询参数中获取
  const userIdParam = request.nextUrl.searchParams.get('userId');
  if (!userIdParam) {
    throw new Error('用户未登录');
  }
  return userIdParam
};

// 获取用户收藏的视频列表
export async function GET(request: NextRequest) {
  try {
    const userId = getCurrentUserId(request);
    const { searchParams } = new URL(request.url);
    const limit = parseInt(searchParams.get('size') || '20');
    const page = parseInt(searchParams.get('page') || '1');
    const offset = (page - 1) * limit;

    const favorites = await VideoService.getUserFavorites(userId, limit, offset);

    return NextResponse.json({
      success: true,
      data: favorites,
      pagination: {
        size: limit,
        page: page
      }
    });
  } catch (error) {
    console.error('获取收藏列表失败:', error);
    return NextResponse.json({
      success: false,
      message: error instanceof Error ? error.message : '获取收藏列表失败',
      error: error instanceof Error ? error.message : '未知错误'
    }, { status: 500 });
  }
}

// 添加或取消收藏
export async function POST(request: NextRequest) {
  try {
    const userId = getCurrentUserId(request);
    const body = await request.json();
    const { videoId, isFavorite } = body;

    // 验证参数
    if (!videoId || typeof isFavorite !== 'boolean') {
      return NextResponse.json({
        success: false,
        message: '参数错误：缺少videoId或isFavorite'
      }, { status: 400 });
    }

    // 执行收藏操作
    await VideoService.toggleFavorite(userId, videoId, isFavorite);

    return NextResponse.json({
      success: true,
      message: isFavorite ? '收藏成功' : '取消收藏成功',
      data: { videoId, isFavorite }
    });
  } catch (error) {
    console.error('操作收藏失败:', error);
    return NextResponse.json({
      success: false,
      message: error instanceof Error ? error.message : '操作收藏失败',
      error: error instanceof Error ? error.message : '未知错误'
    }, { status: 500 });
  }
}